<template>
  <div class="app-container">
    <!-- 搜索表单，通过flex布局实现一行显示 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="search-form">
      <el-form-item label="所属一级分类" prop="parentId">
        <el-select
          v-model="queryParams.parentId"
          placeholder="请选择一级分类"
          clearable
          @change="handleQuery"
          style="width: 180px;"
        >
          <!-- 遍历一级分类列表，显示名称，绑定id -->
          <el-option
            v-for="item in categoryTopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入二级分类名"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['recipes:categories:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['recipes:categories:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['recipes:categories:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recipes:categories:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 二级分类表格 -->
    <el-table v-loading="loading" :data="categoriesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <!-- 显示所属一级分类名称，需后端返回parentName字段 -->
      <el-table-column label="所属一级分类" align="center" prop="categoryTop.name" />
      <el-table-column label="二级分类名" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['recipes:categories:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['recipes:categories:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改二级分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="所属一级分类" prop="parentId">
          <el-select
            v-model="form.parentId"
            placeholder="请选择一级分类"
            clearable
          >
            <el-option
              v-for="item in categoryTopList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类名" prop="name">
          <el-input v-model="form.name" placeholder="请输入二级分类名" />
        </el-form-item>
        <!-- 仅修改时显示状态选择框 -->
        <el-form-item label="状态" prop="status" v-if="form.id">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入二级分类相关API
import { listCategories, getCategories, delCategories, addCategories, updateCategories } from "@/api/recipes/categories"
// 导入一级分类API，用于获取一级分类列表
import { listCategory_top } from "@/api/recipes/category_top"

export default {
  name: "Categories",
  // 注册字典，用于状态显示
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 加载状态
      loading: true,
      // 选中的二级分类id数组
      ids: [],
      // 单个选中禁用修改按钮标识
      single: true,
      // 多个选中禁用删除按钮标识
      multiple: true,
      // 是否显示搜索区域
      showSearch: true,
      // 总记录数
      total: 0,
      // 二级分类列表数据
      categoriesList: [],
      // 一级分类列表（用于下拉选择）
      categoryTopList: [],
      // 弹窗标题
      title: "",
      // 弹窗显示标识
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        // 一级分类id查询参数
        parentId: null
      },
      // 表单数据
      form: {},
      // 表单校验规则
      rules: {
        // 所属一级分类必填校验
        parentId: [
          { required: true, message: "所属一级分类不能为空", trigger: "change" }
        ],
        // 二级分类名必填校验
        name: [
          { required: true, message: "二级分类名不能为空", trigger: "blur" }
        ],
        // 状态必填校验（仅修改时生效）
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        // 排序必填校验
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    // 页面创建时加载二级分类列表和一级分类列表
    this.getList()
    this.getCategoryTopList()
  },
  methods: {
    // 获取二级分类列表
    getList() {
      this.loading = true
      listCategories(this.queryParams).then(response => {
        this.categoriesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 获取一级分类列表
    getCategoryTopList() {
      listCategory_top().then(response => {
        this.categoryTopList = response.rows
      })
    },
    // 取消弹窗
    cancel() {
      this.open = false
      this.reset()
    },
    // 重置表单
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        status: null, // 重置时清空状态
        sort: null
      }
      this.resetForm("form")
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据变化
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      // 新增时默认状态设为0（启用）
      this.form.status = 0
      this.open = true
      this.title = "添加二级菜谱分类"
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCategories(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改二级菜谱分类"
      })
    },
    // 提交表单（新增/修改）
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCategories(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCategories(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 删除按钮操作
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除二级菜谱分类编号为"' + ids + '"的数据项？').then(function() {
        return delCategories(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 导出按钮操作
    handleExport() {
      this.download('recipes/categories/export', {
        ...this.queryParams
      }, `categories_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
/* 搜索表单样式，使其在一行显示 */
.search-form {
  display: flex;
  align-items: center;
}

/* 调整表单元素间距和宽度 */
.el-form-item {
  margin-right: 10px;
}

.el-input, .el-select {
  width: 180px;
}
</style>
